﻿using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data.SqlClient;
using System.Collections.Generic;

public partial class UserControl_ControlPermissionOfUser : System.Web.UI.UserControl
{
    private string str = webapp4U.Configuration.CurrentConnectionString;
    private string error = "";
    ClassExecute.ClassExecute dt;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //nằm trong thread
            ThreadStart ths1 = new ThreadStart(GetUserType);
            //ThreadStart ths2 = new ThreadStart(GetPermissionOfUser);
            Thread th1 = new Thread(ths1);
            //Thread th2 = new Thread(ths2);
            th1.Start();
            //th2.Start();

            th1.Join();
            //th2.Join();
            //nằm trong thread

            DataBindMenuPage();
        }
        MessageBox.ShowOnPageLoad = false;
        MessageBoxUserGroup.ShowOnPageLoad = false;
    }

    public void DataBindMenuPage()
    {
        // hien thi bao nhieu hinh tren 1 trang
        dt = new ClassExecute.ClassExecute();
        DataTable tbMenu = dt.Get_Data_DataTable(str, ref error, "TTr_MenuGetAll", CommandType.StoredProcedure);
        rptCategory.DataSource = tbMenu;
        rptCategory.DataBind();

    }
    protected DataTable tbListPageMenu(string MenuID)
    {
        string strTypeID = "";
        try
        {
            strTypeID = ddlThuocNhom.SelectedValue;
        }
        catch
        {
        }
        dt = new ClassExecute.ClassExecute();
        DataTable tbMenuPage = dt.Get_Data_DataTable(str, ref error, "TTr_Page_GetAllByMenu", CommandType.StoredProcedure,
            new SqlParameter("@MenuID", MenuID),
            new SqlParameter("@TypeID", strTypeID));
        return tbMenuPage;
    }

    void ClearAdd()
    {
        TabContainer1.ActiveTabIndex = 0;
        txtTypeID.Text = "";
        txtTypeID.ReadOnly = false;
        txtTypeID.Focus();
        txtTypeName.Text = "";

        ViewState["flag"] = true;
        
        btnSave.Text = "Lưu";
        lblMsg.Text = "";
        lblMsg.Visible = false;
    }

    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        ClearAdd();
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }

    protected void grvGroupUser_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        if (e.CommandName == DRMConstants.COMMAND_NAME_ROW_COMMAND)
        {
            GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
            Label lblTypeID = (Label)grv.FindControl("lblTypeID");
            Label lblTypeName = (Label)grv.FindControl("lblTypeName");


            txtTypeID.Text = lblTypeID.Text;
            txtTypeName.Text = lblTypeName.Text;

            txtTypeID.ReadOnly = true;
            ViewState["flag"] = false;

            grvGroupUser.DataSource = null;
            grvGroupUser.DataBind();

            lblMsg.Text = "";
            lblMsg.Visible = false;
            btnSave.Text = "Cập nhật";

            TabContainer1.ActiveTabIndex = 0;
        }
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }

    protected void btSearch_Click(object sender, EventArgs e)
    {
        LoadGrid();
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }

    protected void btnAddGroup_Click(object sender, EventArgs e)
    {
        ClearAdd();
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }

    protected void grvGroupUser_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvGroupUser.PageIndex = e.NewPageIndex;
        LoadGrid();
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }
    private void LoadGrid()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "TTr_searchUserType", CommandType.StoredProcedure,
                new SqlParameter("@content", txtSearch.Text));


            if (db.Rows.Count == 0)
            {
                ShowMessageBox("Không tìm thấy kết quả");
            }
            else
            {
                grvGroupUser.DataSource = db;
            }
            grvGroupUser.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        int result = 0;
        try
        {
            if ((bool)ViewState["flag"])
            {
                //insert

                result = dt.ExecuteSQl_int(str, "TTr_UserTypeDirectSale_Insert", CommandType.StoredProcedure, ref error,
                           new SqlParameter("@TypeID", txtTypeID.Text),
                           new SqlParameter("@TypeName", txtTypeName.Text));
                if (result == 1)
                {
                    ClearAdd();
                    lblMsg.Text = "Thêm mới nhóm người dùng thành công";
                    lblMsg.Visible = true;
                    GetUserType();
                }
                else if (result == 2)
                {
                    lblMsg.Text = "Mã nhóm này đã có trong hệ thống";
                    lblMsg.Visible = true;
                }
                else
                {
                    lblMsg.Text = "Thêm mới nhóm người dùng thất bại";
                    lblMsg.Visible = true;
                }
                
            }
            else
            {
                //update
                result = dt.ExecuteSQl_int(str, "TTr_UserTypeDirectSale_Update", CommandType.StoredProcedure, ref error,
                   new SqlParameter("@TypeID", txtTypeID.Text),
                    new SqlParameter("@TypeName", txtTypeName.Text));

                if (result == 1)
                {
                    lblMsg.Text = "Cập nhật nhóm người dùng thành công";
                    lblMsg.Visible = true;
                    GetUserType();
                }
                else
                {
                    lblMsg.Text = "Cập nhật nhóm người dùng thất bại";
                    lblMsg.Visible = true;
                }
            }
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
        MessageBoxUserGroup.ShowOnPageLoad = true;
    }



    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }

    void GetUserType()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getUserTypeList", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlThuocNhom, "TypeID", "TypeName");
        
    }

    

    //void GetPermissionOfUser()
    //{
    //    dt = new ClassExecute.ClassExecute();
    //    DataTable db = dt.Get_Data_DataTable(str, ref error, "D_ACCESS_getPermissionOfUser", CommandType.StoredProcedure,
    //        new SqlParameter("@TypeID", ddlThuocNhom.SelectedValue)
    //    );
    //    chblPageList.DataSource = db;
    //    chblPageList.DataBind();

    //    List<PermissionOfUser> permissionOfUsers = new List<PermissionOfUser>();
    //    permissionOfUsers = ToListObject(db);
    //    foreach (ListItem item in chblPageList.Items)
    //    {
    //        item.Selected = permissionOfUsers.Find(u => u.PageID == int.Parse(item.Value)).IsChecked;
    //    }
    //}

    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        string PageID, TypeID;
        TypeID = ddlThuocNhom.SelectedValue;
        int countItemSelected = 0;
        int countInsertItemSelected = 0;
        int countNotInsertItemSelected = 0;

        for (int i = 0; i < rptCategory.Items.Count; i++)
        {
            GridView gv = rptCategory.Items[i].FindControl("gvMenuPage") as GridView;
            for (int j = 0; j < gv.Rows.Count; j++)
            {
                GridViewRow row = gv.Rows[j];
                bool Ischeck = ((CheckBox)row.FindControl("checkPage")).Checked;
                PageID = ((Label)row.FindControl("lblPageID")).Text;
                if (Ischeck)
                {
                    countItemSelected = countItemSelected + 1;
                    if (!IsAccess(TypeID, PageID))
                    {
                        if (Insert(TypeID, PageID))
                            countInsertItemSelected = countInsertItemSelected + 1;
                    }
                    else
                    {
                        countNotInsertItemSelected = countNotInsertItemSelected + 1;
                    }
                }
                else
                {
                    if (IsAccess(TypeID, PageID))
                    {
                        Delete(TypeID, PageID);
                    }
                }
            }

        }

        if (countItemSelected == (countInsertItemSelected + countNotInsertItemSelected))
        {
            ShowMessageBox("Cập nhật phân quyền người dùng thành công");
        }
        else
        {
            ShowMessageBox("Cập nhật phân quyền người dùng thất bại");
        }
        

    }
    protected void ddlThuocNhom_SelectedIndexChanged(object sender, EventArgs e)
    {
        //ThreadStart ths2 = new ThreadStart(GetPermissionOfUser);
        //Thread th2 = new Thread(ths2);
        //th2.Start();
        //th2.Join();
        DataBindMenuPage();
    }


    private List<PermissionOfUser> ToListObject(DataTable dt)
    {
        List<PermissionOfUser> rel = new List<PermissionOfUser>();

        foreach (DataRow r in dt.Rows)
        {
            rel.Add(new PermissionOfUser
            {
                PageID = int.Parse(r["PageID"].ToString()),
                PageName = r["PageName"].ToString(),
                IsChecked = bool.Parse(r["IsChecked"].ToString())
            });
        }
        return rel;
    }    

    private bool IsAccess(string TypeID, string PageID)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "D_Access_getAccess", CommandType.StoredProcedure
            , new SqlParameter("@TypeID", TypeID)
            , new SqlParameter("@PageID", PageID));
        if (db.Rows.Count > 0)
        {
            return true;
        }
        else 
        {
            return false;
        }
    }

    private bool Delete(string TypeID, string PageID)
    {
        try
        {
            dt = new ClassExecute.ClassExecute();
            return dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "D_Access_delete", ref error
                , new SqlParameter("@TypeID", TypeID)
                , new SqlParameter("@PageID", PageID));
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
            return false;
        }   
    }

    private bool Insert(string TypeID, string PageID)
    {
        try
        {
            dt = new ClassExecute.ClassExecute();
            return dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "D_Access_Insert", ref error
                , new SqlParameter("@TypeID", TypeID)
                , new SqlParameter("@PageID", PageID));
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
            return false;
        }   
    }
}

public class PermissionOfUser
{
    public int PageID { get; set; }
    public string PageName { get; set; }
    public bool IsChecked { get; set; }
}